package com.leyou.order.controller;

import com.leyou.common.exception.LyException;
import com.leyou.common.exception.enums.ExceptionEnum;
import com.leyou.common.pojo.PageResult;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.service.OrderService;
import com.leyou.order.vo.OrderVO;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单接口
     *
     * @param orderDTO      接收请求的参数
     * @param bindingResult 异常校验结果
     * @return 返回订单ID
     */
    @PostMapping("/order")
    public ResponseEntity<Long> createOrder(@Valid @RequestBody OrderDTO orderDTO, BindingResult bindingResult) {
        // 手动从user中取出值来进行判空等校验： 服务器端校验
        if (bindingResult.hasErrors()) {
            // 如果有异常，收集异常信息
            String errors = bindingResult.getAllErrors()
                    .stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(errors, 400);
        }
        // 创建订单
        Long orderId = orderService.createOrder(orderDTO);
        // 返回
        return ResponseEntity.ok(orderId);
    }

    /**
     * 根据订单编号查询订单
     *
     * @param orderId 订单编号
     * @return OrderVO对象
     */
    @GetMapping("/order/{id}")
    public ResponseEntity<OrderVO> findOrderById(@PathVariable("id") Long orderId) {
        OrderVO orderVO = orderService.findOrderById(orderId);
        return ResponseEntity.ok(orderVO);
    }

    /**
     * 获取微信支付的链接
     *
     * @param orderId
     * @return
     */
    @GetMapping("/order/url/{id}")
    public ResponseEntity<String> findPayUrl(@PathVariable("id") Long orderId) {
        String payUrl = orderService.findPayUrl(orderId);
        return ResponseEntity.ok(payUrl);
    }

    /**
     * 查询订单的状态
     *
     * @param orderId 订单编号
     * @return 返回订单的状态
     */
    @GetMapping("/order/state/{id}")
    public ResponseEntity<Integer> findOrderState(@PathVariable("id") Long orderId) {
        Integer state = orderService.findOrderState(orderId);
        return ResponseEntity.ok(state);
    }

    /**
     * 订单中心 - 订单分页查询（我的订单）
     *
     * @param page   当前页
     * @param rows   页大小
     * @param status 是否有状态
     * @param key    搜索条件
     * @return 返回当前分页的数据
     * <p>
     * 2020年5月27日10:22:26
     */
    @GetMapping("list")
    @ApiOperation(value = "分页查询当前用户订单，并且可以根据订单状态过滤", notes = "分页查询当前用户订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页", defaultValue = "1", type = "Integer"),
            @ApiImplicitParam(name = "rows", value = "每页大小", defaultValue = "5", type = "Integer"),
            @ApiImplicitParam(name = "status", value = "订单状态：1未付款，" +
                    "2已付款未发货，" +
                    "3已发货未确认，" +
                    "4已确认未评价，" +
                    "5交易关闭，" +
                    "6交易成功，已评价", defaultValue = "1", type = "Integer"),
            @ApiImplicitParam(name = "key", value = "搜索条件", defaultValue = "", type = "String"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "订单的分页结果"),
            @ApiResponse(code = 404, message = "没有查询到结果"),
            @ApiResponse(code = 500, message = "服务器异常")
    })
    public ResponseEntity<PageResult<OrderVO>> findOrdersByUserId(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "key", required = false) String key
    ) {
        PageResult<OrderVO> result = this.orderService.findOrdersByUserId(page, rows, status, key);
        if (result == null) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return ResponseEntity.ok(result);
    }

}
